package xin.clips.web.controller.gy.analy;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xin.clips.common.annotation.VisistLog;
import xin.clips.common.core.controller.BaseController;
import xin.clips.common.core.domain.AjaxResult;
import xin.clips.common.core.domain.entity.SysDictData;
import xin.clips.common.core.page.TableDataInfo;
import xin.clips.common.enums.gy.DeviceStatusEnum;
import xin.clips.common.enums.gy.DeviceTypeEnum;
import xin.clips.system.domain.SysLogininfor;
import xin.clips.system.domain.SysVisitLog;
import xin.clips.system.domain.gy.GyDevice;
import xin.clips.system.domain.gy.GyDeviceAlarmRecord;
import xin.clips.system.domain.gy.GyDeviceEarlywarnRecord;
import xin.clips.system.service.ISysDictDataService;
import xin.clips.system.service.ISysLogininforService;
import xin.clips.system.service.ISysUserService;
import xin.clips.system.service.ISysVisitLogService;
import xin.clips.system.service.gy.IGyDeviceAlarmRecordService;
import xin.clips.system.service.gy.IGyDeviceEarlywarnRecordService;
import xin.clips.system.service.gy.IGyDeviceService;

import java.text.NumberFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备预警、告警分析
 *
 * @author clips
 * @date 2023-03-15
 */
@Controller
@RequestMapping("/gy/deviceStatusAnaly")
public class DeviceStatusAnalyController extends BaseController {

    private String prefix = "gy/deviceStatusAnaly";

    @Autowired
    private IGyDeviceAlarmRecordService gyDeviceAlarmRecordService;

    @Autowired
    private IGyDeviceService deviceService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysLogininforService logininforService;

    @Autowired
    private ISysVisitLogService visitLogService;

    @Autowired
    private IGyDeviceEarlywarnRecordService gyDeviceEarlywarnRecordService;


    @RequiresPermissions("gy:deviceStatusAnaly:count")
    @VisistLog(title = "设备告警、预警分析")
    @GetMapping()
    public String deviceStatusAnaly(ModelMap mmap) {
        //每日预警、告警折线图
        Map<String, String> alarmDayMap = new HashMap<>(); //登录量 每日统计数据，key是日期，value是值，默认值是0.
        Map<String, String> warningDayMap = new HashMap<>(); //访问量 每日统计数据，key是日期，value是值，默认值是0.
        List<String> dateList = new ArrayList<>();
        String startTime = "";
        String endTime = "";
        for (int i = 7; i >= 0; i--) {
            String date = LocalDate.now().minusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (i == 7) {
                startTime = date;
            }
            if (i == 0) {
                endTime = date;
            }
            dateList.add(date);
            alarmDayMap.put(date, "0");
            warningDayMap.put(date, "0");
        }
        GyDeviceAlarmRecord gyDeviceAlarmRecord = new GyDeviceAlarmRecord();
        gyDeviceAlarmRecord.getParams().put("beginTime", startTime + " 00:00:00");
        gyDeviceAlarmRecord.getParams().put("endTime", endTime + " 23:59:59");

        List<GyDeviceAlarmRecord> alarmRecords = gyDeviceAlarmRecordService.selectAlarmDayAnalyByTime(gyDeviceAlarmRecord);
        for (GyDeviceAlarmRecord alarmRecord : alarmRecords) {
            alarmDayMap.put(alarmRecord.getDat(), alarmRecord.getCount().toString()); //将取到的数据覆盖初始的
        }
        ArrayList<String> alarmCountArray = new ArrayList<>();
        for (String date : dateList) {
            alarmCountArray.add(alarmDayMap.get(date)); //将值转换为string集合。
        }

        //预警每日
        GyDeviceEarlywarnRecord earlywarnRecord = new GyDeviceEarlywarnRecord();
        earlywarnRecord.getParams().put("beginTime", startTime + " 00:00:00");
        earlywarnRecord.getParams().put("endTime", endTime + " 23:59:59");

        List<GyDeviceEarlywarnRecord> earlywarnRecordsr = gyDeviceEarlywarnRecordService.selectEarlyWarnDayAnalyByTime(earlywarnRecord);

        for (GyDeviceEarlywarnRecord visitLog : earlywarnRecordsr) {
            warningDayMap.put(visitLog.getDat(), visitLog.getCount().toString());
        }

        ArrayList<String> warningCountArray = new ArrayList<>();
        for (String date : dateList) {
            warningCountArray.add(warningDayMap.get(date)); //将值转换为string集合。
        }

        mmap.put("warningCountArray", warningCountArray.toArray());
        mmap.put("rqArray", dateList.toArray());//日期array
        mmap.put("alarmCountArray", alarmCountArray.toArray());


        int deviceTotal = deviceService.selectTotal();
        //分类告警占比
        int armProportion = 0; //机械臂告警数量
        int machineProportion = 0;   //机床告警数量
        GyDevice gyDevice = new GyDevice();
        gyDevice.setDeviceStatus(DeviceStatusEnum.WARNING.getCode());
        List<GyDevice> gyDevices = deviceService.selectGyDeviceList(gyDevice);


        for (GyDevice device : gyDevices) {
            if (device.getDeviceType().toString().equals(DeviceTypeEnum.MACHINE.getCode().toString())) {
                machineProportion += 1;
            } else if (device.getDeviceType().toString().equals(DeviceTypeEnum.ARM.getCode().toString())) {
                armProportion += 1;
            }
        }
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(2);

        mmap.put("alarmProportionTotal", deviceTotal);
        mmap.put("machineProportion", numberFormat.format((float) machineProportion / (float) deviceTotal * 100));
        mmap.put("armProportion", numberFormat.format((float) armProportion / (float) deviceTotal * 100));


        //分类预警占比
        int armErrorTotal = 0; //机械臂预警数量
        int machineErrorTotal = 0;   //机床预警数量
        gyDevice = new GyDevice();
        gyDevice.setDeviceStatus(DeviceStatusEnum.ERROR.getCode());
        gyDevices = deviceService.selectGyDeviceList(gyDevice);


        for (GyDevice device : gyDevices) {
            if (device.getDeviceType().toString().equals(DeviceTypeEnum.MACHINE.getCode().toString())) {
                machineErrorTotal += 1;
            } else if (device.getDeviceType().toString().equals(DeviceTypeEnum.ARM.getCode().toString())) {
                armErrorTotal += 1;
            }
        }

        mmap.put("alarmProportionTotal", deviceTotal);
        mmap.put("machineError", numberFormat.format((float) machineErrorTotal / (float) deviceTotal * 100));
        mmap.put("armError", numberFormat.format((float)   armErrorTotal / (float) deviceTotal * 100));

        return prefix + "/deviceStatusAnaly";
    }


    /**
     * 设备状态分析
     */
    @RequiresPermissions("gy:deviceStatusAnaly:count")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GyDeviceAlarmRecord gyDeviceAlarmRecord) {

        startPage();
        List<GyDeviceAlarmRecord> list = gyDeviceAlarmRecordService.selectGyDeviceAlarmRecordList(gyDeviceAlarmRecord);
        return getDataTable(list);
    }

    /**
     * 导出设备消息绑定列表
     */
    @RequestMapping("search")
    @ResponseBody
    public AjaxResult search(String startTime, String endTime) {


        List<String> dateList = new ArrayList<>();
        Map<String, String> alarmDayMap = new HashMap<>();
        Map<String, String> warningDayMap = new HashMap<>();

        dateList.add(startTime);
        warningDayMap.put(startTime, "0");
        warningDayMap.put(startTime, "0");
        String date = startTime;
        do {
            date = LocalDate.parse(date).plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            dateList.add(date);
            warningDayMap.put(date, "0");
            warningDayMap.put(date, "0");
        } while (!endTime.equals(date));


        GyDeviceAlarmRecord gyDeviceAlarmRecord = new GyDeviceAlarmRecord();
        gyDeviceAlarmRecord.getParams().put("beginTime", startTime + " 00:00:00");
        gyDeviceAlarmRecord.getParams().put("endTime", endTime + " 23:59:59");

        List<GyDeviceAlarmRecord> alarmRecords = gyDeviceAlarmRecordService.selectAlarmDayAnalyByTime(gyDeviceAlarmRecord);
        for (GyDeviceAlarmRecord alarmRecord : alarmRecords) {
            alarmDayMap.put(alarmRecord.getDat(), alarmRecord.getCount().toString()); //将取到的数据覆盖初始的
        }
        ArrayList<String> alarmCountArray = new ArrayList<>();
        for (String temp : dateList) {
            alarmCountArray.add(alarmDayMap.get(date)); //将值转换为string集合。
        }

        //预警每日
        GyDeviceEarlywarnRecord earlywarnRecord = new GyDeviceEarlywarnRecord();
        earlywarnRecord.getParams().put("beginTime", startTime + " 00:00:00");
        earlywarnRecord.getParams().put("endTime", endTime + " 23:59:59");

        List<GyDeviceEarlywarnRecord> earlywarnRecordsr = gyDeviceEarlywarnRecordService.selectEarlyWarnDayAnalyByTime(earlywarnRecord);

        for (GyDeviceEarlywarnRecord visitLog : earlywarnRecordsr) {
            warningDayMap.put(visitLog.getDat(), visitLog.getCount().toString());
        }

        ArrayList<String> warningCountArray = new ArrayList<>();
        for (String temp : dateList) {
            warningCountArray.add(warningDayMap.get(date)); //将值转换为string集合。
        }


        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("warningCountArray", warningCountArray.toArray());  //登录量[]
        ajaxResult.put("rqArray", dateList.toArray());//日期array
        ajaxResult.put("alarmCountArray", alarmCountArray.toArray()); //访问量[]

        return ajaxResult;
    }

}



